#include "tm1640.h"
#include "i2c.h"
#include "systimer.h"

const uint8_t tm1640_addr[] = {0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF};

static uint8_t code[16]; 
static void i2c_start(void)
{
	i2c2_start();
}

static void i2c_send_byte(uint8_t byte)
{
	i2c2_send_byte(byte);
}

static void i2c_stop(void)
{
	i2c2_stop();
}

#if 0	
static void tm1640_send_data(uint8_t cmd, uint8_t addr, uint8_t data)
{
    i2c_start();
    i2c_send_byte(cmd);
    i2c_stop();
    i2c_start();
    i2c_send_byte(addr);
    i2c_send_byte(data);
    i2c_stop();
}

static void tm1640_send_data_fixed(uint8_t addr, uint8_t *buf, uint8_t len)
{
    i2c_start();
    i2c_send_byte(TM1640_CMD_DATA_FIXED);
    i2c_stop();
    i2c_start();
    while(len--)
    {
        i2c_send_byte(addr);
        i2c_send_byte(*buf++);
    }
    i2c_stop();
}
#endif

static void tm1640_send_data_plus(uint8_t addr, uint8_t *buf, uint8_t len)
{
    i2c_start();
    i2c_send_byte(TM1640_CMD_DATA_PLUS);
    i2c_stop();
    i2c_start();
    i2c_send_byte(addr);
    while(len--)
    {
        i2c_send_byte(*buf++);
    }
    i2c_stop();
}

void tm1640_set_luminance(uint8_t cmd)
{
    i2c_start();
    i2c_send_byte(cmd);
    i2c_stop();
}

/* 此处数据长度写定9字节，后续要记得更改，长度应与len相同 */
void tm1640_set_output(uint8_t *buf, uint8_t len)
{
    for(uint8_t i = 0; i < len; i++)
    {
        if(code[i] != buf[i])
        {
            code[i] = buf[i];
            tm1640_send_data_plus((uint8_t)tm1640_addr[i], &code[i], 1);
        }
    }
}

// static void tm1640_set_full(void)
// {
//     uint8_t  buf[9] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
//     tm1640_set_output(buf, 9);
// }

// static void tm1640_set_clear(void)
// {
//     uint8_t buf[9] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
//     tm1640_set_output(buf, 9);
// }

// void tm1640_self_test(void)
// {
// 	tm1640_set_luminance(TM1640_CMD_LIGHT_4_16);
// 	tm1640_set_full();
//     delay_ms(2000);
//     tm1640_set_clear();
//     delay_ms(500);
// }
